<template>
  <div class="login">
    <div class="in" v-if="showLogin">
      <div class="logo">
        <div>
          <img style="width: 30px;height: 30px;" alt="" :src="logoUrl">
        </div>
        <div>
          <text class="title">教务微信登录</text>
        </div>
      </div>
      <div class="from">
        <nut-form ref="ruleForm" :model-value="formData">
          <nut-form-item required prop="name" :rules="[{ required: true, message: '请输入用户名' }]">
            <nut-input left-icon="people" v-model="formData.name" class="nut-input-text" placeholder="请输入账号"
                       type="text"/>
          </nut-form-item>
          <nut-form-item required prop="pwd" :rules="[{ required: true, message: '请输入密码' }]">
            <nut-input left-icon="marshalling" v-model="formData.pwd" class="nut-input-text" placeholder="请输入密码"
                       type="password"/>
          </nut-form-item>

          <div class="btn">
            <nut-button v-if="checkWay == '1' || checkWay == '3'" color="#0081FF" block type="info" @click="loginBD()">
              本地认证
            </nut-button>
            <nut-button v-if="checkWay == '2' || checkWay == '3'" color="#0081FF" round block plain type="primary"
                        @click="loginTY()"> 统一认证
            </nut-button>
          </div>

          <div class="xieyi">
            <text class="text-grey1">登录即代表同意</text>
            <text @click="handleUserAgrement()" class="text-blue">《用户协议》</text>
          </div>
        </nut-form>
      </div>
    </div>

  </div>
</template>

<script>
import {getLogoUrl, getUserByBD, getUserByCode, getUserByTY, getUserInfo} from '/src/api/index'
import {useRouter} from 'vue-router';

const router = useRouter();
import {useUserStore} from "/src/store/modules/user";

import {Notify} from 'vant';
import 'vant/es/notify/style';
import * as http from "http";

const authorWay = import.meta.env.VITE_APP_AUTHOR_WAY;

export default {
  computed: {
    http() {
      return http
    }
  },
  setup() {
    const router = useRouter();
    const state = reactive({
      tab1value: '0'
    });

    const data = reactive({
      filePath: '',
      checkWay: authorWay,
      showLogin: false,
      showLoading: true
    });

    const initFlag = () => {
      /*const tag = localStorage.getItem('showLogin');
      if (tag === "noLogin"){
        data.showLogin = true;
        console.log('showI');
      }*/
    };

    const getPath = async () => {
      const tag = localStorage.getItem('showLogin');

      data.filePath = ''
      setTimeout(() => {
        data.showLogin = true;
        data.showLoading = false;
      }, 800);
    };

    onMounted(() => {
      initFlag();
      getPath();
    })

    const handleUserAgrement = () => {
      router.push('/yhxy');
    }

    return {
      state,
      ...toRefs(data),
      handleUserAgrement,
    };
  },
  data() {
    return {
      // 测试
      userStore: useUserStore(),
      router: useRouter(),
      logoUrl: getLogoUrl(),
      formData: {
        name: '',
        pwd: '',
      }
    };
  },
  async created() {
    Notify({
      message: '自动登录中...',
      type: 'primary',
      background: '#1989fa',
      duration: 700,
    });

    var url = window.location.href;             //获取当前url


    //找到id，测试时候注释
    var cs = url.split('?')[1];
    console.log('cs1:', cs)
    var cs_arr = cs.split('&');
    var cs = {};
    for (var i = 0; i < cs_arr.length; i++) {
      cs[cs_arr[i].split('=')[0]] = cs_arr[i].split('=')[1]
    }
    console.log('cs1:', cs)

    localStorage.setItem('openIdFlag', "isOpen")
    localStorage.setItem('showLogin', "noLogin")
    console.log('show1')
    const p = localStorage.getItem('loginflag')
    if (p === "loginold") {
      localStorage.setItem('showLogin', "isLogin");
    }
    // 查询信息并转json
    let userStore = useUserStore()
    //userStore.setUserLoginToken(cs.account)
    const res = await getUserByCode(cs.code);
    console.log('BycodeLogin:', res)

    let code = res.response.value.code;
    if (500 == code) {
      alert(res.response.value.msg);
    } else {
      let info = res.response.value.extend
      userStore.setUserType(info.TYPE)
      if (info.TYPE == 'stud') {
        userStore.setInfo(info.userInfo, info.TYPE)
        localStorage.setItem("userType", info.TYPE)
        localStorage.setItem('showLogin', "isLogin");
        this.router.push('/mainMenu');
      } else if (info.TYPE == 'tea') {
        // this.userSt
        // ore.setUserType(1)
        localStorage.setItem("userType", info.TYPE)
        localStorage.setItem('showLogin', "isLogin");
        console.log('teacher', info);
        userStore.setInfo(info.userInfo, info.TYPE)
        this.router.push('/mainMenu_tea');
      } else {
        //身份信息错误
        alert('身份信息错误')
      }
    }

  },
  methods: {
    async loginBD() {

      let userStore = useUserStore();
      const {name, pwd} = this.formData; // 获取用户名和密码
      const res = await getUserByBD(name, pwd);
      console.log('loginBD: ', res)
      console.log('loginBD: ', res.response.value.extend)

      let info = res.response.value.extend

      console.log('BDinfo', info);

      userStore.setUserType(info.TYPE)
      if (info.TYPE === 'stud') {
        userStore.setInfo(info.userInfo, info.TYPE)
        localStorage.setItem("userType", info.TYPE)
        this.router.push('/mainMenu');
      } else if (info.TYPE === 'tea') {
        localStorage.setItem("userType", info.TYPE)
        console.log('teacher', info);
        userStore.setInfo(info.userInfo, info.TYPE)
        this.router.push('/mainMenu_tea');
      } else {
        //身份信息错误
        alert('身份信息错误')
      }
    },

    async loginTY() {

      let userStore = useUserStore();
      const {name, pwd} = this.formData; // 获取用户名和密码
      const res = await getUserByTY(name, pwd);
      console.log('loginTY: ', res.response.value.extend)

      let info = res.response.value.extend
      console.log('BDinfo', info);

      userStore.setUserType(info.TYPE)
      if (info.TYPE === 'stud') {
        userStore.setInfo(info.userInfo, info.TYPE)
        localStorage.setItem("userType", info.TYPE)
        this.router.push('/mainMenu');
      } else if (info.TYPE === 'tea') {
        localStorage.setItem("userType", info.TYPE)
        console.log('teacher', info);
        userStore.setInfo(info.userInfo, info.TYPE)
        this.router.push('/mainMenu_tea');
      } else {
        //身份信息错误
        alert('身份信息错误')
      }
    },
  },
};
</script>

<style scoped lang="less">
.login {
  height: 100%;
  background: #fff;
  padding: 0 2.5rem;

  .in {
    .logo {
      width: 100%;
      font-size: 1.4rem;
      text-align: center;
      padding-top: 30%;
      margin-bottom: 8vh;
      display: flex;
      justify-content: center;

      .title {
        margin-left: 15px;
      }
    }

    .nut-form-item {
      background: #F5F6F7;
      height: 10vw;
      border-radius: 1.5rem;
      margin-bottom: 2.5vh;
      display: flex;
      justify-content: center;
      padding: 1.2vw 3vw;
      //input {
      //  background:3.4-4.2 transparent;
      //}
    }

    .xieyi {
      text-align: center;
      margin-top: 1.5rem;

      .text-grey1 {
        color: #888888;
        font-size: 0.9rem;
      }

      .text-blue {
        font-size: 0.9rem; /* 设置字体大小为16像素 */
        color: #0081FF; /* 设置字体颜色为蓝色 */
      }
    }

    .btn :nth-child(2) {
      margin-top: 1rem;
    }

    .input.input-text {
      margin-left: 10px;
    }
  }
}

/deep/ .nut-form-item__body {
  display: flex;
  justify-content: center;
}

/deep/ .nut-input-box {
  padding: 0 30px;
}

/deep/ .input-text {
  font-size: 0.8rem;
  color: #888888;
}
</style>
